<?php
/**
 * Created by PhpStorm.
 * User: function
 * Date: 2018-04-12
 * Time: 9:09
 */

namespace app\common\logic;
use app\common\logic\Logic;
use app\common\model\Company;
use app\common\model\Goods;
use app\common\model\Visit;
use app\common\model\CoType;
class CompanyLogic extends Logic
{
    protected $modelClass = 'app\common\model\Company';
    protected $column = 'user_id,company,city_id,is_club,club_id,validated,thumb,business,status';
    
    /**
     * @param null $catid
     * @param null $title
     * @param null $keyword
     * @param null $price
     * @return mixed
     */
    public function getList($params){
        
        $this->setSql($params);
        $lists = parent::prepareDataProvider();
        
        //获取额外参数
        if(isset($params['mallSize'])&&$params['mallSize']>0){
            foreach ($lists as $company){
                $company['malls'] = $this->getMall($company->user_id,$params['mallSize']);
            }
        }
        return $lists;
        
    }
    
    /**
     * @param $itemid
     * @param null $field
     * @param $mall 是否需要返回推荐的商品，如果该值为真，则返回店里十个按排名的商品
     * @return mixed
     */
    public function getOne($userId,$mallSize=null){

        $rt = Company::get(['user_id'=>$userId]);
        
        //点击量
        $rt->hits++;
        $rt->isUpdate()->save();
        
        //访问记录
        $visit = new Visit();
        $visit->c_id = $rt->user_id;
        $visit->save();
        
        $rt['type'] = CoType::all(['co_id'=>$userId]);
        
        //如果需要获取商品的
        if($mallSize&&$mallSize>0){
            $rt['malls'] = $this->getMall($rt->user_id,$mallSize);
        }
        return $rt;
    }
    
    /**
     * find model
     * @param $id
     * @return mixed
     */
    public function findModel($user_id=null){
        
        $modelClass = $this->modelClass;
        $condition['user_id']=$user_id?$user_id:$this->$user_id;
        var_dump($condition);die;
        //关联
        if($this->with){
            $query = $modelClass::with($this->with)->where($condition);
        }else{
            $query = $modelClass::where($condition);
        }
        
        
        // 筛选字段
        if($this->field){
            $query = $query->field($this->field);
        }
        
        $model = $query->find();
        
        //自动加点击数
        if(isset($model['hits'])){
            $model->hits +=1;
            $model->isUpdate()->save();
        }
        
        if(!$model){
            error("你没权限操作或该记录已经被删除！");
        }
        return $model;
    }
    
    
    protected function getMall($companyId,$limit){
        
        $query = Goods::where('user_id',$companyId)->field('id,title,price,marketprice,thumb');
        if($limit>0){
            $query = $query->limit($limit);
        }
        $rt = $query->select();
        return $rt;
    }
    
    
    
}